from channels.db import database_sync_to_async
from chat.models import ChatUser, ChatGroup
from django.contrib.auth.models import AnonymousUser
from django.http.request import QueryDict
from typing import Optional


@database_sync_to_async
def get_user(user_id) -> Optional[ChatUser]:
    try:
        return ChatUser.objects.get(id=user_id)
    except ChatUser.DoesNotExist:
        return None


@database_sync_to_async
def get_group(group_id) -> Optional[ChatGroup]:
    """查询是否存在群组"""
    try:
        return ChatGroup.objects.get(id=group_id)
    except ChatGroup.DoesNotExist:
        return None


class QueryAuthMiddleware:
    """
    自定义用户websocket认证中间价
    """

    def __init__(self, app):
        # Store the ASGI application we were passed
        self.app = app

    async def __call__(self, scope, receive, send):
        query_params = QueryDict(scope["query_string"].decode())

        scope["group"] = await get_group(int(query_params.get("group_id", 0)))
        scope['user'] = await get_user(int(query_params.get("user_id", 0)))

        return await self.app(scope, receive, send)